﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Manso.cBot.Common
{
    /// <summary>
    /// Module manager of cBot. In normal scenario you dont need to use this class.
    /// </summary>
    public class ModuleManager
    {
        private readonly Dictionary<String, IModule> _modules;
        private readonly CommandManager _commandManager;

        public ModuleManager()
        {
            _modules = new Dictionary<string, IModule>();
            _commandManager = new CommandManager();
        }

        public bool AddModule(IModule module)
        {
            // Check if module with same name is already loaded
            if (_modules.ContainsKey(module.Name.ToLower())) return false;

            // Check that no command in module share same name with commands already loaded
            foreach (ICommand command in module.Commands)
            {
                if (_commandManager.Contains(command)) return false;
            }

            // Load all command from module on command manager
            foreach (ICommand command in module.Commands)
            {
                _commandManager.AddCommand(command);
            }

            // Load module on module manager
            module.Load();
            _modules.Add(module.Name.ToLower(), module);
            return true;
        }
        
        public bool RemoveModule(IModule module)
        {    
            // Unload all command from command manager
            foreach (ICommand command in module.Commands)
            {
                _commandManager.RemoveCommand(command);
            }

            // Unload module from module manager
            _modules.Remove(module.Name.ToLower());
            module.Unload();
            return true;
        }

        public ICommand GetCommand(String command, ListenToEnum listenTo)
        {
            return _commandManager.GetCommand(command, listenTo);            
        }

        public IEnumerable<IModule> Modules
        {
            get
            {
                return _modules.Values;
            }            
        }
    }
}
